package com.iqik.sc.ns.service;

import com.iqik.sc.ns.dao.TokenRepository;
import com.iqik.sc.pojo.Token;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.Optional;
import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private TokenRepository tokenRepository;

    @Override
    public String getToken(String email) {
        Token token = new Token();
        token.setEmail(email);
        Optional<Token> result = tokenRepository.findOne(Example.of(token));
        return result.isEmpty() ? null : result.get().getToken();
    }

    @Override
    public String createToken(String email) {
        Token token = new Token();
        token.setEmail(email);
        Optional<Token> result = tokenRepository.findOne(Example.of(token));
        if (result.isPresent()) {
            Token newToken = result.get();
            newToken.setEmail(email);
            newToken.setToken(getUUID());
            return tokenRepository.saveAndFlush(newToken).getToken();
        } else {
            token.setToken(getUUID());
            return tokenRepository.saveAndFlush(token).getToken();
        }
    }

    @Override
    public String getEmailByToken(String token) {
        Token source = new Token();
        source.setToken(token);
        Optional<Token> result = tokenRepository.findOne(Example.of(source));
        return result.isEmpty() ? null : result.get().getEmail();
    }

    String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }
}
